package repository

import (
	"errors"
	"github.com/jinzhu/gorm"
	"go_shengshu_admin/model"
	"go_shengshu_admin/query"
	"go_shengshu_admin/utils"
	"time"
)

type UserRepository struct {
	DB *gorm.DB
}

type UserRepoInterface interface {
	List(req *query.ListQuery) (users []*model.User, err error)
	GetTotal() (total int64, err error)
	Get(user model.User) (*model.User, error)
	Exist(user model.User) *model.User
	ExistByUserId(id string) *model.User
	ExistByMobile(user model.User) *model.User
	Add(user model.User) (*model.User, error)
	Edit(user model.User) (bool, error)
	Delete(id string) (bool, error)
}

func (p *UserRepository) List(req *query.ListQuery) (users []*model.User, err error) {
	db := p.DB
	limit, offset := utils.Page(req.PageSize, req.Page)
	if err := db.Order("id desc").Limit(limit).Offset(offset).Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

func (p *UserRepository) GetTotal() (total int64, err error) {
	var users []model.User
	db := p.DB
	if err := db.Find(&users).Count(&total).Error; err != nil {
		return 0, err
	}
	return total, nil
}

func (p *UserRepository) Get(user model.User) (*model.User, error) {
	if err := p.DB.Where(&user).Find(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (p *UserRepository) Exist(user model.User) *model.User {
	var count = 0
	p.DB.Find(&user).Where("nick_name = ?", user.NickName).Count(&count)
	if count > 0 {
		return &user
	}
	return nil
}

func (p *UserRepository) ExistByUserId(id string) *model.User {
	var user *model.User
	var count = 0
	p.DB.Find(&user).Where("user_id = ?", id).Count(&count)
	if count > 0 {
		return user
	}
	return nil
}

func (p *UserRepository) ExistByMobile(user model.User) *model.User {
	var count = 0
	p.DB.Find(&user).Where("mobile = ?", user.Mobile).Count(&count)
	if count > 0 {
		return &user
	}
	return nil
}

func (p *UserRepository) Add(user model.User) (*model.User, error) {
	user.CreateAt, _ = time.Parse(utils.TimeLayout, utils.GetNow())
	user.UpdateAt, _ = time.Parse(utils.TimeLayout, utils.GetNow())
	if exist := p.Exist(user); exist != nil {
		return nil, errors.New("用户已存在")
	}
	if err := p.DB.Create(&user).Error; err != nil {
		return nil, errors.New("创建用户失败")
	}
	return &user, nil
}

func (p *UserRepository) Edit(user model.User) (bool, error) {
	if err := p.DB.Model(&user).Where("user_id = ?", user.UserId).Updates(map[string]interface{}{
		"nickname": user.NickName,
		"mobile":   user.Mobile,
		"address":  user.Address}).Error;
		err != nil {
		return false, err
	}
	return true, nil
}

func (p *UserRepository) Delete(id string) (bool, error) {
	var user *model.User
	if err := p.DB.Model(&user).Where("user_id = ?", id).Update(
		"is_deleted", user.IsDeleted).Error; err != nil {
		return false, err
	}
	return true, nil
}
